package org.xtense.engine.actions;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;

import org.xtense.data.DBManager;
import org.xtense.engine.IConstants;
import org.xtense.exception.XtenseException;
import org.xtense.log.iLog;

public abstract class XAction {
	protected DBManager database;
	protected String documentName;
	protected int documentID;
	
	protected XAction(String documentName) {
		this(new DBManager(), documentName);
	}

	protected XAction(DBManager manager, String documentName) {
		this.database = manager;
		this.documentName = documentName;
	}
	
	protected XAction(DBManager manager, int documentID) {
		this.database = manager;
		this.documentID = documentID;
		if (documentID < 0) {
			try {
				throw new XtenseException(XtenseException.NoSuchDoc);
			} catch (XtenseException e) {
				iLog.warn(e);
			}
		}
	}

	protected static int getDocumentIDfromName(DBManager dbmanager, String name) {
		String exp = MessageFormat.format(IConstants.Sql_String_Equal,
				new Object[] { IConstants.Document_Name, name });
		String sql = MessageFormat.format(IConstants.Sql_Select_One,
				new Object[] { IConstants.Document_ID,
						IConstants.Document_Table, exp });
		ResultSet res = dbmanager.executeSqlQuery(sql);
		int id = -1;
		if (res != null) {
			try {
				while (res.next()) {
					id = res.getInt(1);
				}
			} catch (SQLException e) {
				iLog.error(e);
			}
		}

		return id;
	}
	
	public abstract Object execute(Object object);
	
}
